package cn.edu.suda.catalina.dataupdate.service.implement;

import cn.edu.suda.catalina.dataupdate.domain.SystemUserRepository;
import cn.edu.suda.catalina.dataupdate.entity.SystemRole;
import cn.edu.suda.catalina.dataupdate.entity.SystemUser;
import cn.edu.suda.catalina.dataupdate.service.SystemUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Spring Security 使用的 service
 * @author admin
 */
@Service("userDetailsService")
public class SystemUserServiceImpl implements UserDetailsService, SystemUserService {
    @Autowired
    private SystemUserRepository repository;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        SystemUser user = repository.findByUsername(s);
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在！");
        }
        List<SystemRole> roles = user.getRoles();
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (SystemRole role : roles) {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        return new User(user.getUsername(), user.getPassword(), authorities);
    }

    @Override
    public SystemUser save(SystemUser user) {
        return repository.save(user);
    }
}
